<template>
  <div class="kanban-main-warp animated need-main-container" style="display: block;">
    <div class="kanban-main-container content">
      <div class="kanbanCard-main-container">
        <div class="cardList-container-warp">
          <ul class="cardList-container ui-sortable second-type-container">
            <!--添加建议列-->
            <li class="kanban-card-container list-today animated">
              <div class="kanban-card-container">
                <div class="kanban-card-warp">
                  <div class="card-table">
                    <div class="head-tr">
                      <div class="header not-active" style="display: block;">
                        <div class="attr"><span>{{activeIndex?'编辑':'新增'}}{{model['name']}}</span></div>
                      </div>

											<i class="icon-close addBtn" style="display: inline;top: 12px;" v-if="activeIndex" @click="resetForm()" title="取消编辑"></i>

                    </div>
                    <div class="body-tr">
                      <div class="body-tr-container">
                        <div class="kanban-item-warp">
                          <ul class="list-ul doing ui-sortable"
                              style="min-height: 100px;width: 100%">
                            <li class="kanban-Item-container animated tooltipstered add-advice-container"
                                style="padding: 0px;border:0;background: transparent;">
                              <el-row :gutter="10">
                                <el-col :span="24">
                                  <el-input v-model="title" placeholder="请输入标题"></el-input>
                                </el-col>

                              </el-row>
                              <el-row :gutter="10">
                                <el-col :span="24">
                                  <el-input v-model="desc" placeholder="请输入内容" type="textarea" :rows="4"></el-input>
                                </el-col>

                              </el-row>
                              <!-- <el-row :gutter="10">
                                <el-col :span="24">
                                  <el-input v-model="phoneNum" placeholder="请输入手机号"></el-input>
                                </el-col>

                              </el-row>
                              <el-row :gutter="10">
                                <el-col :span="6">录音</el-col>
                                <el-col :span="18"><i class="el-icon-menu">长按录音</i></el-col>

                              </el-row> -->
                              <el-row :gutter="10" v-if="!activeIndex">
                                <el-col :span="24">
                                  <el-button v-on:click="addData" type="primary" size="small"
                                             style="color:#fff;display: block;width:100%">添加
                                  </el-button>
                                </el-col>

                              </el-row>
                              <el-row :gutter="10" v-else>
                                <el-col :span="24">
                                  <el-button v-on:click="updateData" type="primary" size="small"
                                             style="color:#fff;display: block;width:100%">修改
                                  </el-button>
                                </el-col>

                                <el-col :span="24" style="margin:10px 0 0 0;">
                                  <el-button v-on:click="delData" type="danger" size="small" style="color:#fff;display: block;width:100%">
                                    <i class="el-icon-delete"></i> 删除
                                  </el-button>
                                </el-col>


                              </el-row>
                              


                            </li>
                          </ul>

                        </div>

                      </div>
                    </div>
                  </div>

                  <div class="footer">
                    <!--今日三种模式点击-->
                    <div class="switch-type-contaienr" >
                      <span @click="changeShowType(1)" :class="switchType==1?'active':''">建议</span>
                      <span @click="changeShowType(2)" :class="switchType==2?'active':''">需求</span>
                    </div>
                  </div>
                  
                </div>
              </div>
            </li>
            <!--建议列-->
            <li class="kanban-card-container list-today animated" data-card-id="today" :key="item1.id" v-for="(item1, index) in containList">
              <div class="kanban-card-container">
                <div class="kanban-card-warp">
                  <div class="card-table">
                    <div class="head-tr">
                      <div class="header not-active" style="display: block;">
                        <div class="attr"><span>{{item1.value}}</span></div>
                      </div>

                    </div>
                    <div class="body-tr">
                      <div class="body-tr-container">
                        <div class="kanban-item-warp">
                          <ul class="list-ul doing ui-sortable"
                              style="min-height: 100px;width: 100%">
                            <draggable class="dragArea today-task-list" :list="item1.list" tagKey="due"
                                       :anotherkey1="item1.key" anotherValue1='' :tagVal="daySelect"
                                       :options="{group:'task'}" @end="saveSort" @add="dragEvent">
                              <li :class="'kanban-Item-container animated tooltipstered '+(item2.id==activeIndex?'active':'')" :key="item2.id"
                                  v-for="item2 in need[item1.key+ model['class']]" v-on:click="editDetail(item2, index)"
                                  draggable="false">
                                <p class="ad-title">{{item2.title}}</p>
                                <p class="ad-desc">{{item2.desc}}</p>
                                <span style="display: none">{{item2.id}}</span>
                                <div class="ad-btn-container" >
                                  <i v-on:click="likeOrUnlike(item2.id,'like',item1.key+model['class'])"
                                     class="iconfont icon-zan ad-btn" @click.stop>{{item2.like?item2.like:0}}</i>
                                  <i v-on:click="likeOrUnlike(item2.id,'unlike',item1.key+model['class'])"
                                     class="iconfont icon-daocai ad-btn" @click.stop>{{item2.unlike?item2.unlike:0}}</i>
                                  <div class="pay-btn ad-btn">
                                    <el-popover ref="popover" placement="top" width="150" trigger="hover">
                                      <img src="../../../static/images/avatar.png" alt=""
                                           style="width:150px;height:150px;"/>
                                      <i class="el-icon-warning ad-btn" slot="reference">{{item2.pay?item2.pay:0}}</i>
                                    </el-popover>

                                  </div>
                                </div>
                              </li>
                            </draggable>
                          </ul>
                        </div>
                        <div class="no-task-container" v-show="false">
                          <img src="../../../static/z39pc/assets/images/no-task.png" alt=""/>
                          <p>点击添加新需求</p>
                          <p>或使用+号添加新需求</p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="footer">
                    <div class="bottom" style="display:block">
                      {{model['name']}}:<template v-if="need[item1.key+ model['class']]">{{need[item1.key+ model['class']].length}}</template>
                    </div>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>


    <div class="task-detail-container">
      <!--<task-detail ref="showTaskDetail"></task-detail>-->
      <task-detail ref="taskDetailComponent"></task-detail>
    </div>



  </div>

</template>

<script>//	import ms from 'ms'
import draggable from 'vuedraggable'
import taskDetail from '../../components/task/taskDetail.vue'
import {mapState} from 'vuex'

import store from '../../store'

export default {
  props: ['switchType'],
  components: {
    'task-detail': taskDetail,
    draggable
  },
  data() {
    return {
      title: '',
      desc: '',
      phoneNum: '',

      model:{
        name: '',
        class: '',
        key: ''
      },


      // todayTags: [],
      timeDotDialogVisible: false,
      selectTimeDot: '',
      selectedTaskId: '',
      dragItemData: '',
      quickNoStr: "QWERTYUIOP",
      showTimeNeed: false,
      showPopupPicker: false,
      showSummary: false,
      taskCurr: {
        title: ""
      },
      taskDoing: null,
      sortStr: "",
      todayArr: [],
      visibility: false,
      showMonth: '',

      stateAdd: false,
      taskTitle: "",
      taskDesc: "",
      smyTitle: "",
      smydesc: "",
      smydesc1: "",
      smydesc2: "",
      smydesc3: "",
      smydesc4: "",
      smydesc5: "",
      showAddTag: false,

      activeIndex:''
      //switchType:2,
      // need: {
      //   need: [],
      //   doneneed: [],
      //   doingneed: [],
      //   okneed: [],
      //   notneed: [],
      // },
      // needAndAdvice: {},
      // pid: '',
    };

  },
  // mixins: [taskAndTag, mixinPc],
  computed: {
    ...mapState({
      uid: state => state.vux.uid,
      minDate: state => state.z39.minDate,
      maxDate: state => state.z39.maxDate,
      taskAll: state => state.z39.taskAll,
      tagDic: state => state.z39.tagDic,
      taskDic: state => state.z39.taskDic,
      tagitems: state => state.z39.tagitems,
      tagitemDic: state => state.z39.tagitemDic,
      days: state => state.z39.days,
      projects: state => state.z39.projects,
      members: state => state.z39.members,
      todayTags: state => state.z39.tagtmps,
      memberDic: state => state.z39.memberDic,
      daySelect: state => state.z39.selectedDayDate,
      filterTaskState: state => state.z39.filterTaskState,
    }),
    containList(){
      return [{
        key: '',
        value: '用户'+this.model['name']+'(还未处理) ',
      }, {
        key: 'done',
        value: '已完成'+this.model['name'],
      }, {
        key: 'doing',
        value: '近期执行(已采纳)',
      }, {
        key: 'ok',
        value: '已采纳',
      }, {
        key: 'not',
        value: '未采纳(不考虑)',
      }];
    },
    need(){
      console.log('need()');
      if(!this.model['name']){
        return [{'a':[]}]; 
      }
      console.log(store.state.needAndAdvice);
      let need = {};
      this.containList.forEach(item => {
        need[item.key + this.model['class']] = store.state.needAndAdvice[item.key + this.model['class']];
      });
      return need;
    }
  },
  watch: {
    // "taskAll": {
    //   handler() {
    //     // this.resort();
    //   },
    //   deep: true,
    // },
    // "daySelect": function () {
    //   // this.resort();
    // },
    // "tagitems": {
    //   handler() {
    //     var temp = [];
    //     var len = this.tagitems.length;
    //     for (var i = 0; i <= len - 1; i++) {
    //       var item = this.tagitems[i];
    //       temp.push({
    //         key: item.key,
    //         name: item.name
    //       });
    //     }
    //
    //     // this.getTagTmpList();
    //   },
    //   deep: true,
    // },
    // todayTags: {
    //   handler() {
    //     // this.getTagTmpList();
    //   },
    //   deep: true,
    // },
    "$route": function (to, from) {
      this.initPage();
    },
    // filterTaskState: function () {
    //   // this.resort();
    // }
  },
  created() {

  },
  filters: {},
  methods: {
    async changeShowType(type){
      let page = (type==1?'advice':'need');

      if(store.state.needAndAdvice.pid!=20) page+='?pid='+store.state.needAndAdvice.pid;

      this.$parent.linkToPage(page);
    },
    resetForm(){
      this.activeIndex = '';
      this.title    = '';
      this.desc     = '';
      this.phoneNum = '';
    },
    editDetail(item, index){
      if(index>0) return ;
      
      this.activeIndex = item.id;
      this.title    = item.title;
      this.desc     = item.origDesc;
      this.phoneNum = item.phoneNum;
    },
    /**
     * 判断pid是否修改来更新需求建议
     * @returns {Promise<void>}
     */
    async initPage(){
      this.resetForm();
      let pid = this.$route.query['pid'];
      if(!pid) pid = 20;
      
      let data ={
        1:{name:'建议',class:'advice',key:'suggest'},
        2:{name:'需求',class:'need',key:'demand'},
      };

      this.model = data[this.switchType];


      store.commit('setPid', pid);
      store.commit('empty', this.model['class']);
      store.dispatch('queryAdviceOrNeed', { key: this.model['key'], rand:Math.random()});

    },
    /**
     * 赞或踩
     * @param taskid
     * @param key
     * @param taskType
     * @returns {Promise<void>}
     */
    async likeOrUnlike(taskid, key, taskType) {
      let data = {
        taskType: taskType,
        taskid: taskid,
        key: key
      };
      let res = await
        store.dispatch('likeOrUnlike', data);
      this.$message({
        message: res ? res : '成功',
        type: res ? 'warning' : 'info'
      });
    },
    /**
     * 修改需求和建议
     * @returns {Promise<void>}
     */
    async updateData(){
      let data = {
        title: this.title,
        desc: this.desc,
        phoneNum: this.phoneNum,
        id:this.activeIndex
      };
      console.log(data);
      let res = await store.dispatch('updateAdviceOrNeed', data);
      this.$message({
        message: res ? res : '成功',
        type: res ? 'warning' : 'info'
      });
      if (res === false) {
        this.resetForm();
      }
    },
    /**
     * 删除需求和建议
     * @returns {Promise<void>}
     */
    async delData(item){

      let data = {
        id:this.activeIndex
      };

      this.$confirm('该操作不可恢复，确认删除？',  '警告', {type: 'warning'})
          .then(async () => {
            let res = await store.dispatch('delAdviceOrNeed', data);
            this.$message({
              message: res ? res : '成功',
              type: res ? 'warning' : 'info'
            });
            if (res === false) {
              this.resetForm();
            }
          })
          .catch(() => {});


    },
    /**
     * 添加需求和建议
     * @returns {Promise<void>}
     */
    async addData() {
      let data = {
        title: this.title,
        desc: this.desc,
        phoneNum: this.phoneNum,
        state: this.model['key'],
      };
      let res = await store.dispatch('addAdviceOrNeed', data);
      this.$message({
        message: res ? res : '成功',
        type: res ? 'warning' : 'info'
      });
      if (res.succ) {
        this.title = '';
        this.desc = '';
        this.phoneNum = '';
      }
    },
    /**
     * 拖拽事件
     * @param ev
     * @returns {Promise<void>}
     */
    async dragEvent(ev) {
      //移动的需求id
      let id = ev.clone.childNodes[4].innerText;
      // 处理标签
      let fromKey = ev.from.attributes.anotherkey1.value;
      let toKey = ev.to.attributes.anotherkey1.value;

      let need = {
        id: id,
        fromKey: fromKey,
        toKey: toKey,
        key: this.model['key'],
      };
      let res = await store.dispatch('updateAdviceOrNeedTag', need);
      this.$message({
        message: res ? res : '成功',
        type: res ? 'warning' : 'info'
      });
      if (!res.succ) {
        //todo 拖拽失败后的处理
      }
    },
    /**
     * 保存排序
     * @param ev
     * @param list
     * @returns {Promise<void>}
     */
    async saveSort(ev) {
      let fromKey = ev.from.attributes.anotherkey1.value;
      let toKey = ev.to.attributes.anotherkey1.value;
      console.log('从', fromKey, '到', toKey);
      if (fromKey !== toKey) return;
      let idList = '';
      ev.from.childNodes.forEach(item => {
        idList += `${item.childNodes[4].innerText},`
      });
      console.log('移动后的list', idList);
      localStorage.setItem(`${fromKey}needsort`, idList);
    }
  },
  mounted() {
    console.log('mounted');
    this.initPage();
    this.needAndAdvice = store.state.needAndAdvice;
  }
}</script>
<style>
  .need-main-container .kanban-item-warp ul li .el-row:not(:last-child) {
    margin-bottom: 10px;
    line-height: 36px;
  }

  .need-main-container .kanban-item-warp ul li .el-row:last-child {
    text-align: right;
  }
</style>
